<template>
  <div class="app-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
            <el-col :span="24">      
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>编辑试卷</span>
                </div>
                <div>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="考试部门" prop="deptList">
                        <treeselect v-model="form.deptList" prop="deptList" :options="deptOptions" :multiple="true" :normalizer="normalizer" placeholder="请选择考试部门" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="名称" prop="paperName" required>
                        <el-input v-model="form.paperName" placeholder="请输入名称" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="类型" prop="paperType" required>
                      <el-select v-model="form.paperType" placeholder="请选择类型">
                        <el-option
                          v-for="dict in dict.type.paper_type"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10" v-if="form.paperType==0||form.paperType==1">
                      <el-form-item label="考试时间">
                      <el-date-picker
                          v-model="paperTime"
                          type="datetimerange"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" v-if="form.paperType==1">
                      <!-- <el-form-item label="总分" prop="paperScore">
                        {{form.paperScore}}
                      </el-form-item> -->
                      <el-form-item label="时长(分)" prop="duration">
                        <el-input-number v-model="form.duration" :min="1"  placeholder="请输入时长"  required/>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="考试模式" prop="patternList">
                        <el-checkbox-group v-model="form.patternList" size="small" >
                          <el-checkbox-button v-for="dict in dict.type.paper_pattern" :label="dict.value" :key="dict.value">{{dict.label}}</el-checkbox-button>
                        </el-checkbox-group>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="阅卷人" prop="grades">
                          <el-button :key="index" v-for="(grade,index) in form.gradeUsers" type="primary" plain  size="mini" @click="form.gradeUsers.splice(index,1)">{{grade.userName+'-'+grade.nickName}}<i class="el-icon-delete el-icon--right"></i></el-button>
                          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="questionGradeUsers()">添加</el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </el-card>    
            </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>组卷策略</span>
                </div>
                <div>
                  <el-row>
                    <el-container>
                      <el-aside width="400px">
                        <el-row>
                          <el-form-item label="选择题库：" label-width="120px"  prop="sectionList">
                            <treeselect v-model="sectionList" size="small" prop="deptList"  :options="repoOptionsSelect"  :multiple="true" :normalizer="normalizerRepo"  placeholder="请选择题库" />
                          </el-form-item>
                        </el-row>
                        <el-row>
                          <el-form-item label="选择难度：" label-width="120px"  prop="levelList">
                            <el-select v-model="levelList" multiple clearable placeholder="难度" style="width:100%">
                                <el-option 
                                v-for="dict in dict.type.question_level"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                                ></el-option>
                              </el-select>
                          </el-form-item>
                        </el-row>
                        <el-form-item label="题型：" label-width="120px" prop="questionType">
                          <el-select  v-model="questionType" placeholder="请选择题型" clearable>
                            <el-option
                              v-for="dict in dict.type.question_type"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                        <el-row>
                          <el-form-item label="题数："  label-width="120px" >
                            <el-input-number v-model="questionAmount"  size="mini" :min="0.0"  placeholder="题数"/>
                          </el-form-item>
                        </el-row>
                        <el-row>
                          <el-form-item label="分值："  label-width="120px" >
                            <el-input-number v-model="defaultScore"  size="mini" :min="0.0"  placeholder="分值"/>
                          </el-form-item>
                        </el-row>
                        <el-row>
                          <el-button type="success" @click="configAdd">添加</el-button>
                        </el-row>
                      </el-aside>
                      <el-container>
                          <el-main>
                            <el-table :data="configList">
                              <el-table-column label="题库" align="center" key="sectionList" prop="sectionList" width="250px">
                                <template slot-scope="scope">
                                  <treeselect v-model="scope.row.sectionList" size="small" prop="deptList"  :options="repoOptionsSelect"  :multiple="true" :normalizer="normalizerRepo" disabled  placeholder="题库" />
                                </template>
                              </el-table-column>
                              <el-table-column label="难度" align="center" key="levelList" prop="levelList" width="200px">
                                <template slot-scope="scope">
                                  <dict-tag :options="dict.type.question_level" :value="scope.row.levelList"/>
                                </template>
                              </el-table-column>
                              <el-table-column label="题型" align="center" key="questionType" prop="questionType" :show-overflow-tooltip="true">
                                <template slot-scope="scope">
                                  <dict-tag :options="dict.type.question_type" :value="scope.row.questionType"/>
                                </template>
                              </el-table-column>
                              <el-table-column label="题数" align="center" key="questionAmount" prop="questionAmount" :show-overflow-tooltip="true" />
                              <el-table-column label="分值" align="center" key="defaultScore" prop="defaultScore" :show-overflow-tooltip="true" />
                              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                <template slot-scope="scope">
                                  <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-delete"
                                    @click="configRemove(scope.$index)"
                                  >删除</el-button>
                                </template>
                              </el-table-column>
                            </el-table>
                          </el-main>
                          <el-footer>
                            <el-row >
                              <el-button type="primary" @click="submitForm">确 定</el-button>
                              <el-button @click="cancel">取 消</el-button>
                            </el-row>
                          </el-footer>
                      </el-container>
                    </el-container>
                  </el-row>
                 
                </div>
              </el-card>
            </el-col>
        </el-row>
        
      </el-form>

    <el-dialog :visible.sync="openUser" width="60%" append-to-body>
      <el-col :span="20" :xs="24">
        <el-form :model="queryUserParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="姓名" prop="userName">
            <el-input
              v-model="queryUserParams.userName"
              placeholder="姓名"
              clearable
              @keyup.enter.native="handleUserQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-table  ref="userTable"  v-loading="loading" :data="userList" @select="handleSelectioUserChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
          <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
          <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
          <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
        </el-table>
        <pagination
        v-show="totalUser>0"
        :total="totalUser"
        :page.sync="queryUserParams.pageNum"
        :limit.sync="queryUserParams.pageSize"
        @pagination="getUserList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getPaper, delPaper, createPaper, updatePaper, editPaper } from "@/api/paper/paper";
import { listRepo } from "@/api/paper/repo";
import {  allocatedUserList } from "@/api/system/role";
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "Paper",
  components: { Treeselect },
  dicts: ['question_type','paper_status','paper_type','question_level','paper_pattern'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //用户数
      totalUser: 0,
      groups: [],
      sectionList: [],
      questionType: null,
      questionAmount: 0,
      defaultScore: 0,
      levelList: [],
      // 弹出层标题
      title: "1",
      openUser: false,
      // 是否显示难度设置
      showLevel: false,
      // 是否显示题库设置
      showRepo: false,
      // 是否显示分数设置
      showScore: false,
      // 部门树选项
      deptOptions: [],
      // 题库章节 
      repoOptionsSelect: [],     
      // 试题表格数据
      questionList: [],
      // 用户表格数据
      userList: [],
      // 试题配置表格数据
      configList: [],
      // 考试起止时间
      paperTime: [],
      //当前组index
      groupIndex: 0,
      paperConfigs: [],
      patterns: [],
      // 查询参数
      queryUserParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        roleId: null,
      },
      // 表单参数
      form: {},
      questionForm: {},
      // 表单校验
      rules: {
        paperName: [
          { required: true, message: "试卷名称不能为空", trigger: "blur" }
        ],
        paperType: [
          { required: true, message: "试卷类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.configList = [];
    this.handleAdd();
    this.handleUpdate(150);
    this.getTreeselect();
  },
  methods: {
    getUserList() {
      this.loading = true;
      this.queryUserParams.roleId = 2;
      allocatedUserList(this.queryUserParams).then(response => {
        this.userList = response.rows;
        this.totalUser = response.total;
        this.loading = false;
        this.$nextTick(()=>{
          this.userList.forEach(row=>{
            this.form.gradeUsers.forEach(grade=>{
              if(grade.userId==row.userId){
                this.$refs.userTable.toggleRowSelection(row,true);
              }
          })
          });
        });      
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        depts: null,
        deptList: [],
        composeStrategy: [],
        sections: null,
        sectionList: [],
        groups: [{ groupName:"2",questions: []}],
        gradeUsers: [],
        paperName: null,
        beginTime: null,
        endTime: null,
        duration: null,
        paperScore: null,
        status: null,
        paperType: null,
        composeType: null,
        grades: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        patternList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleUserQuery() {
      this.queryUserParams.pageNum = 1;
      this.getUserList();
    },
    /** 重置按钮操作 */
    resetUserQuery() {
      this.resetForm("queryUserForm");
      this.handleUserQuery();
    },    
    // 多选框选中数据
    handleSelectioUserChange(selection,row) {
      let selected = selection.length && selection.indexOf(row) !== -1;
      let users=this.form.gradeUsers;
      if(selected){
        users.push({userId:row.userId,userName:row.userName,nickName:row.nickName});
      }else{
        users.forEach((user,index)=>{
          if(row.userId==user.userId){
            users.splice(index,1);
          }
      });
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 查询题库下拉树结构 */
    getTreeselect() {
      this.title = ["1"];
      listRepo().then(response => {
        this.repoOptionsSelect = this.handleTree(response.data, "repoId");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.reset();
      this.getTreeselect();
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
      getPaper(id).then(response => {
        this.form = response.data;
        this.form.composeStrategy = [];
        this.form.patternList = [];
        if(this.form.depts){
          this.form.deptList=[];
          this.form.depts.split(",").forEach(dept=>{this.form.deptList.push(dept)});
        }
        if(!this.form.groups){
          this.form.groups=[{ groupName:'2'}];
        }
        if(!this.form.grades){
          this.form.gradeUsers = [];
        }
        if(this.form.beginTime){
          this.paperTime[0] = this.parseTime(this.form.beginTime);
        }
        if(this.form.endTime){
          this.paperTime[1] = this.parseTime(this.form.endTime);
        }
        if(this.form.patterns){
          this.form.patterns.split(",").forEach(pattern=>{
            this.form.patternList.push(pattern)});
        }
      });     
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let depts = ""
          this.form.deptList.forEach(dept=>{
            depts += dept+","
          })   
          if(depts.length>0){
            depts=depts.substring(0,depts.length-1)
          }
          this.form.depts = depts

          let grades = ""
          this.form.gradeUsers.forEach(grade=>{
            grades += grade.userId+","
          })   
          if(grades.length>0){
            grades=grades.substring(0,grades.length-1)
          }
          this.form.grades = grades
          this.form.beginTime = this.parseTime(this.paperTime[0]);
          this.form.endTime = this.parseTime(this.paperTime[1]);
          this.initPattern();

          if (this.form.id != null) {
            updatePaper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
            });
          } else {
            this.form.configs = this.configList;
            this.form.composeType = "0";
            createPaper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
            });
          }
        }
      });
    },
    /**处理考试模式 */
    initPattern(){
      let patterns = ""
      this.form.patternList.forEach(pattern=>{
        patterns += pattern+",";
      })   
      if(patterns.length>0){
        patterns=patterns.substring(0,patterns.length-1);
      }
      this.form.patterns = patterns;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考试试卷编号为"' + ids + '"的数据项？').then(function() {
        return delPaper(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
     /** 转换试题题库章节数据结构 */
    normalizerRepo(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.repoId,
        label: node.repoName,
        children: node.children
      };
    },
    // 添加标题
    configAdd() {
      this.configList.push({ questionType:this.questionType,sectionList:this.sectionList,
          levelList:this.levelList,questionAmount:this.questionAmount,defaultScore:this.defaultScore});
      let configs = this.form.configs;
      console.log(configs)
      if(configs!=undefined){
       // configs.push({ groupName:'1'});
      }else{
        this.form.configs=[{ groupName:'2',questions: []}];
      }
    },
    configRemove(index){
      //this.form.configs.splice(index,1)
      this.configList.splice(index,1);
    },
    questionGradeUsers(){
      this.openUser = true;
      this.getUserList();
    },  
  }
};
</script>
